<template>
    <div style="width: 100%; height: 100%;">
        <div>
            <div class=" app-container">
                <div class="pageTitle">
                    <div class="pageBtn" style="padding-left: 0;">
                        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
                    </div>
                </div>
                <page-main>
                    <el-table ref="orderTable" v-loading="isLoading" class="actionTable" stripe :data="tableData"
                              header-cell-class-name="table-header" style="width: 100%;" border :row-class-name="tableRowClassName">
                        <el-table-column label="区域ID" width="100" prop="region_id" />
                        <el-table-column label="区域名称" width="150" prop="region_name" />
                        <el-table-column label="关联机构ID" width="150" prop="control_unit_ids" />
                        <el-table-column label="操作" width="150" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" icon="el-icon-edit" style="margin-right: 10px;" @click="handleEdit(scope.row)">修改</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </page-main>
            </div>
        </div>

        <el-dialog :title="currentRegion.isNew?'添加区域':'修改区域'" :visible.sync="detailVisible" width="700px">
            <el-form ref="form" :model="currentRegion" :rules="rules" label-width="120px" size="small">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="区域名称" prop="region_name">
                            <el-input v-model="currentRegion.region_name" placeholder="请输入区域名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="关联组织机构" prop="control_unit_array">
                            <treeselect v-model="currentRegion.control_unit_array" :flat="true" :multiple="true" :normalizer="normalizer" :options="deptList" placeholder="选择组织机构" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="地理位置" prop="region_center">
                            <div style="height: 350px;">
                                <map-point v-model="markerPoint" :init-center="initCenter" />
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="detailVisible = false">取 消</el-button>
                <el-button size="small" :loading="isLoading" type="primary" @click="handleSubmit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import moment from 'moment';
import MapPoint from './MapPoint';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

import {
    InquiryCentralPoint, InsertCentralPoint, SelectAllTcontrolUnit,
    UpdateCentralPoint
} from '@/api/resourceManageApi';
import {handleTree} from '@/util';

export default {
    name: 'region-info-config',
    components: {
        MapPoint, Treeselect
    },
    filters: {

    },
    props: {},
    data() {
        return {
            markerPoint: {},
            initCenter: {},
            isLoading: false,
            tableData: [],
            detailVisible: false,
            currentRegion: {},
            rules: {
                region_name: [
                    { required: true, message: '区域名称不能为空', trigger: 'blur' }
                ],
                control_unit_array: [
                    { required: true, message: '关联组织机构不能为空', trigger: 'blur' }
                ],
                region_center: [
                    { required: true, message: '区域位置必须设置', trigger: 'change' }
                ]
            },
            deptList: []
        };
    },
    computed: {

    },
    watch: {
        markerPoint: {
            deep: true,
            handler(val) {
                if (val && val.lng) {
                    let pointstr = val.lng + ',' + val.lat;
                    this.currentRegion.region_center = pointstr;
                }
                // this.$refs['form'] && this.$refs['form'].clearValidate('latitude');
            }
        }
    },
    created() {

    },
    mounted() {
        this.loadDeptTree();
        this.loadRemoteData();
    },
    methods: {
        moment,
        tableRowClassName({row, rowIndex}) {
            if (this.detailVisible && this.currentRegion.region_id == row.region_id) {
                return 'selected-row';
            }
            return '';
        },
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                isDisabled: !!node.children,
                isDefaultExpanded: true,
                id: node.control_unit_id,
                label: node.name,
                children: node.children
            };
        },
        loadDeptTree() {
            this.isLoading = true;
            SelectAllTcontrolUnit().then(res => {
                this.isLoading = false;
                console.log(res);
                let list = res.res.ControlUnit;
                list[0].parent_id = 0;
                this.deptList = handleTree(list, 'control_unit_id', 'parent_id', 'children', 0);
                console.log(this.deptList);
            }).catch(err => {
                this.isLoading = false;
                console.log(err);
            });
        },
        loadRemoteData() {
            this.isLoading = true;
            InquiryCentralPoint().then(res => {
                this.isLoading = false;
                let result = res.res.InquiryCentralPoint;
                this.tableData = result;
            }).catch(err => {
                this.isLoading = false;
                console.log(err);
            });
        },
        handleAdd() {
            this.currentRegion = {
                isNew: true
            };
            this.markerPoint = {};
            this.initCenter = {...this.markerPoint};
            this.$nextTick(() => {
                this.$refs['form'] && this.$refs['form'].clearValidate();
            });
            this.detailVisible = true;
        },
        handleEdit(item) {
            let region = {...item};
            region.control_unit_array  = region.control_unit_ids.split(',');
            region.control_unit_array = region.control_unit_array.map(Number);
            try {
                let point = JSON.parse(region.region_center);
                this.markerPoint = {lat: point[1], lng: point[0]};
                this.initCenter = {...this.markerPoint};
                region.region_center = point[1] + ',' + point[0];
            } catch (e) {
                console.log(e);
            }
            console.log(region);
            this.currentRegion = region;
            this.detailVisible = true;
            this.$nextTick(() => {
                this.$refs['form'] && this.$refs['form'].clearValidate();
            });
        },
        handleSubmit() {
            if (this.clickTooFast()) return;
            this.$refs['form'].validate(valid => {
                if (valid) {
                    this.isLoading = true;

                    this.currentRegion.control_unit_ids = this.currentRegion.control_unit_array.join(',');

                    if (this.currentRegion.isNew) {
                        InsertCentralPoint(this.currentRegion).then(res => {
                            this.$message.success('添加成功');
                            this.loadRemoteData();
                            this.detailVisible = false;
                            this.isLoading = false;
                        }).catch(err => {
                            this.isLoading = false;
                            console.log(err);
                        });
                    } else {
                        UpdateCentralPoint(this.currentRegion).then(res => {
                            this.$message.success('修改成功');
                            this.loadRemoteData();
                            this.detailVisible = false;
                            this.isLoading = false;
                        }).catch(err => {
                            this.isLoading = false;
                            console.log(err);
                        });
                    }
                }
            });
        }

    }
};
</script>

<style scoped>
/deep/
.vue-treeselect__multi-value-item {
    padding: 0;
}
/deep/
.vue-treeselect--has-value .vue-treeselect__multi-value {
    margin-bottom: 0;
}
.table-header {
    background-color: #f8f8f8 !important;
}
/deep/
.el-table td {
    padding: 5px 0 !important;
}
/deep/
.el-button--text {
    padding: 5px 0;
}
/deep/
.el-dialog__body {
    padding: 10px 20px;
}
/deep/
.el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #dcdfe6;
}
</style>

<style lang="scss" scoped>

.table-header {
    background-color: #f8f8f8 !important;
}
.el-table ::v-deep td {
    padding: 5px 0 !important;
}
.tree-panel {
    margin-left: var(--real-sidebar-width);
    height: calc(100% - 120px);
    position: fixed;
    z-index: 100;
    left: 0;
    width: 260px;
    padding-left: 5px;
    padding-top: 5px;
    background: #fbfbfb;
    border: 1px solid #e5e5e5;
    margin-right: 10px;
}
</style>
